<?php


namespace app\logic\cron;


use app\common\lib\Common;
use app\logic\BaseLogic;
use DateTime;
use plugin\admin\app\model\user\UserRechargeOrderModel;
use support\Db;
use support\Log;

class UserRechargeOrderLogic extends BaseLogic
{
    protected static $instance;

    protected $model;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
        return new self();
    }

    public function statistics()
    {
        Log::info("statistics：-1" );
        //获取今日日期
        $today = new DateTime('today');
        $todayFormat = $today->format('Y-m-d 00:00:00');

        // 获取昨日日期
        $yesterday = new DateTime('yesterday');
        $yesterdayFormat = $yesterday->format('Y-m-d 00:00:00');

        // 获取前日日期（前天）
        $dayBeforeYesterday = new DateTime('2 days ago');
        $dayBeforeYesterdayFormat = $dayBeforeYesterday->format('Y-m-d 00:00:00');

        Log::info("statistics：-2" );
        //昨日充值
        $yesterdayRechargeCount = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $yesterdayFormat)
            ->where('pay_time', '<', $todayFormat)
            ->where('order_status', '=', 6)
            ->sum('money');

        Log::info("statistics：-3" );
        //前日充值
        $dayBeforeYesterdayRechargeCount = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $dayBeforeYesterdayFormat)
            ->where('pay_time', '<', $yesterdayFormat)
            ->where('order_status', '=', 6)
            ->sum('money');

        Log::info("statistics：-4" );
        //昨日续费
        $yesterdayRenewalCount = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $yesterdayFormat)
            ->where('pay_time', '<', $todayFormat)
            ->where('order_status', '=', 6)
            ->where('isrenew', '=', 1)
            ->sum('money');

        Log::info("statistics：-5" );
        //前日续费
        $dayBeforeYesterdayRenewalCount = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $dayBeforeYesterdayFormat)
            ->where('pay_time', '<', $yesterdayFormat)
            ->where('order_status', '=', 6)
            ->where('isrenew', '=', 1)
            ->sum('money');

        Log::info("statistics：-6" );
        //昨日按订单支付类型分组统计
        $paymentGroup = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $yesterdayFormat)
            ->where('pay_time', '<', $todayFormat)
            ->where('order_status', '=', 6)
            ->groupBy("payment")
            ->select('payment', Db::raw('count(payment) as total'))
            ->get();

        Log::info("statistics：-7" );
        //前日按订单支付类型分组统计
        $dayBeforeYesterdayPaymentGroup = UserRechargeOrderModel::getInstance()
            ->where('pay_time', '>=', $dayBeforeYesterdayFormat)
            ->where('pay_time', '<', $yesterdayFormat)
            ->where('order_status', '=', 6)
            ->groupBy("payment")
            ->select('payment', Db::raw('count(payment) as total'))
            ->get();

        $iosRate = 0;
        $androidRate = 0;
        $iosTotal = 0;
        $androidTotal = 0;

        Log::info("statistics：-8" );
        if ($paymentGroup) {
            $paymentGroupArr = $paymentGroup->toArray();
            $temp = array_column($paymentGroupArr, null, 'payment');
            $total = array_sum(array_column($paymentGroupArr, 'total'));
            //payment 1是iOS  3是安卓（数据库写着微信是不对的）
            $iosTotal = $temp[1]['total'] ?? 0;
            $androidTotal = $temp[3]['total'] ?? 0;
            $iosRate = round($iosTotal / $total, 4) * 100;
            $androidRate = round($androidTotal / $total, 4) * 100;
        }


        Log::info("statistics：-9" );
        $dayBeforeYesterdayIosTotal = 0;
        $dayBeforeYesterdayAndroidTotal = 0;
        if ($dayBeforeYesterdayPaymentGroup) {
            $dayBeforeYesterdayPaymentGroupArr = $dayBeforeYesterdayPaymentGroup->toArray();
            $temp = array_column($dayBeforeYesterdayPaymentGroupArr, null, 'payment');
            //payment 1是iOS  3是安卓（数据库写着微信是不对的）
            $dayBeforeYesterdayIosTotal = $temp[1]['total'] ?? 0;
            $dayBeforeYesterdayAndroidTotal = $temp[3]['total'] ?? 0;
        }

        Log::info("statistics：-10" );
        //昨日充值环比
        $yesterdayTopUpRate = $this->revenueDayOverDay($yesterdayRechargeCount, $dayBeforeYesterdayRechargeCount);

        Log::info("statistics：-11" );
        //昨日续费环比
        $yesterdayRenewalRate = $this->revenueDayOverDay($yesterdayRenewalCount, $dayBeforeYesterdayRenewalCount);

        Log::info("statistics：-12" );
        //昨日IOS订单环比
        $yesterdayIOSOrderRate = $this->revenueDayOverDay($iosTotal, $dayBeforeYesterdayIosTotal);

        Log::info("statistics：-13" );
        //昨日安卓订单环比
        $yesterdayAndroidOrderRate = $this->revenueDayOverDay($androidTotal, $dayBeforeYesterdayAndroidTotal);

        $tableData = [
            [
                "label" => "充值",
                "value" => '￥' . $yesterdayRechargeCount,
                "ratio" => $yesterdayTopUpRate
            ],
            [
                "label" => "续费",
                "value" => '￥' . $yesterdayRenewalCount,
                "ratio" => $yesterdayRenewalRate
            ],
            [
                "label" => "IOS订单",
                "value" => $iosTotal,
                "ratio" => $yesterdayIOSOrderRate
            ],
            [
                "label" => "IOS订单占比",
                "value" => $iosRate . '%',
                "ratio" => $yesterdayIOSOrderRate
            ],
            [
                "label" => "Android订单",
                "value" => $androidTotal,
                "ratio" => $yesterdayAndroidOrderRate
            ],
            [
                "label" => "Android订单占比",
                "value" => $androidRate . '%',
                "ratio" => $yesterdayAndroidOrderRate
            ],
        ];

        $templateId = 'AAq7UvKXwECJ3';//在飞书卡片构建后后台复制
        $templateVersionName = '1.0.5';//在飞书卡片构建后后台复制
        $token = '40525817-80dc-4ac5-ac12-7999403366b2';//机器人webhook那里可以拿到
        $templateVariable = [
            'date' => $yesterday->format("Y/m/d"),
            'table_data_array' => $tableData,
        ];

        Log::info("statistics：-14" );
        if (config('app.app_env') == "prod") {
            Log::info("statistics：-15" );
            //正式  https://open.feishu.cn/open-apis/bot/v2/hook/40525817-80dc-4ac5-ac12-7999403366b2
            Common::sendFeiShuCardNotice($templateVariable, $token, $templateId, $templateVersionName);
        }

        Log::info("statistics：-16" );
        if (config('app.app_env') == "test") {
            //开发者接收
            Common::sendFeiShuCardNotice($templateVariable, '10e5bafe-94ae-405e-a1b8-b55e01828d2f', $templateId, $templateVersionName);
        }
        Log::info("statistics：-17" );
        return true;
    }


    /**
     * 环比计算
     * @param $yesterdayRechargeCount
     * @param $dayBeforeYesterdayRechargeCount
     * @return float|int
     */
    public function revenueDayOverDay($yesterdayRechargeCount, $dayBeforeYesterdayRechargeCount)
    {
        // 计算环比增长
        if ($dayBeforeYesterdayRechargeCount > 0) {
            $revenueDayOverDay = round(($yesterdayRechargeCount - $dayBeforeYesterdayRechargeCount) / $dayBeforeYesterdayRechargeCount, 4);
        } elseif ($yesterdayRechargeCount > 0 && $dayBeforeYesterdayRechargeCount == 0) {
            $revenueDayOverDay = 1;
        } elseif ($yesterdayRechargeCount == 0 && $dayBeforeYesterdayRechargeCount > 0) {
            $revenueDayOverDay = -1;
        } else {
            $revenueDayOverDay = 0;
        }

        return ($revenueDayOverDay * 100) . '%';
    }
}